package com.jci.vsd.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.jci.vsd.R;
import com.jci.vsd.application.VsdApplication;
import com.jci.vsd.constant.AppConstant;
import com.jci.vsd.constant.MySpEdit;
import com.jci.vsd.utils.CertServiceUrl;
import com.jci.vsd.utils.Loger;

import com.jci.vsd.view.widget.SimpleToast;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Map;
import butterknife.BindView;
import cn.com.syan.jcee.common.sdk.utils.CertificateConverter;
import cn.com.syan.online.sdk.OnlineApplyResponse;
import cn.com.syan.online.sdk.OnlineClient;
import cn.com.syan.online.sdk.OnlineIssueResponse;
import cn.unitid.spark.cm.sdk.data.entity.CertApplyParam;
import cn.unitid.spark.cm.sdk.exception.CmSdkException;
import cn.unitid.spark.cm.sdk.listener.ProcessListener;

/**
 * Created by liqing on 18/7/10.
 * 申请个人证书 activity
 */

public class RegisterCertActivity extends BaseActivity {
    @BindView(R.id.edt_name)
    EditText edtName;

    @BindView(R.id.edt_id_no)
    EditText edtIdNo;
    @BindView(R.id.edt_tel)
    EditText edtTel;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    //第三方证书的申请客户端
    private OnlineClient onlineClient;

    @BindView(R.id.textview_title)
    TextView tvTitle;

    @BindView(R.id.button_back)
    ImageButton btnBack;

    private String userId;
    private String realName;
    private String idNo;
    private String phone;
    private ProgressDialog progressDialog;
    private MySpEdit prefs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_cert_new);
        //llCert.getBackground().setAlpha(100);//0~255透明度值
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setCancelable(true);

        btnBack.setVisibility(View.GONE);
        tvTitle.setText("申请证书");
        initRegistCert();
        initViewEvent();
        prefs = MySpEdit.getInstance();

    }


    private void initTestData() {
        edtName.setText("李青");
        edtIdNo.setText("320322199007171428");
        edtTel.setText("15951882547");
    }


    private void initTestData2() {
        //  edtAccount.setText("屠正松");

        edtName.setText("张睿");
        edtIdNo.setText("321027199409053017");
        edtTel.setText("13773506614");
//        em.setText("2319345023@qq.com");

    }

    private void initTestDataT() {
        //  edtAccount.setText("屠正松");
        edtName.setText("屠正松");
        edtIdNo.setText("320113199310156418");
        edtTel.setText("15252466554");
//        em.setText("2319345023@qq.com");


//        edtAccount.setText("12");
//        edtPsw.setText("12");
//        edtEmail.setText("245633");
//        edtRealName.setText("王朕");
//        edtUserID.setText("320113199407266410");
//        edtTel.setText("18205188981");

    }

    public void showLoading(String message) {
        progressDialog.setMessage(message);
        progressDialog.show();
    }

    public void hideLoading() {
        if (progressDialog.isShowing()) {
            progressDialog.cancel();
        }
    }


    private void initRegistCert() {
        onlineClient = new OnlineClient(CertServiceUrl.baseUrl,
                CertServiceUrl.appKey, CertServiceUrl.appSecret);

    }

    @Override
    protected void initViewEvent() {
        //点击事件的监听 
        tvSure.setOnClickListener(this);


    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.tv_sure) {

            applyCert();
        }
    }

    private void applyCert() {
        String nameStr = edtName.getText().toString().trim();
        String idNoStr = edtIdNo.getText().toString().trim();
        String telStr = edtTel.getText().toString().trim();
        if (TextUtils.isEmpty(nameStr)) {
            edtName.requestFocus();
            SimpleToast.toastMessage("姓名不可以为空！", Toast.LENGTH_LONG);
            return;
        }

        if (TextUtils.isEmpty(idNoStr)) {
            edtIdNo.requestFocus();
            SimpleToast.toastMessage("身份证号不可以为空！", Toast.LENGTH_LONG);
            return;
        }

        if (TextUtils.isEmpty(telStr)) {
            edtTel.requestFocus();
            SimpleToast.toastMessage("电话号码不可以为空！", Toast.LENGTH_LONG);
            return;
        }

//        if (TextUtils.isEmpty(pin)) {
//            edtPin.requestFocus();
//            SimpleToast.toastMessage("PIN码不可以为空！", Toast.LENGTH_LONG);
//            return;
//        }


        //goRegisterCertify(nameStr, idNoStr, telStr, pin);

        newRegisterCert(nameStr, idNoStr, telStr, "1234");
    }


    private void newRegisterCert(final String realname, final String id, final String tel, final String vcode) {
        CertApplyParam param = new CertApplyParam();
        param.setRealName(realname);
        param.setIdNum(id);
        param.setTelephone(tel);
        param.setvCode(vcode);
        showLoading(getString(R.string.string_applying));
        userId = VsdApplication.getUserId();

        // 证书申请（注册）
        cn.unitid.spark.cm.sdk.business.service.CertificateRegisterService certificateRegisterService = new cn.unitid.spark.cm.sdk.business.service.CertificateRegisterService(userId, AppConstant.SPARK_RA_URL,
                AppConstant.APP_KEY, AppConstant.APP_SECRET, AppConstant.TEMPLATE, new ProcessListener<OnlineApplyResponse>() {
            @Override
            public void doFinish(OnlineApplyResponse onlineApplyResponse, String s) {

//            issueId.setText(onlineApplyResponse.getApplyId());
//            subject.setText(onlineApplyResponse.getSubject());
//            algorithm.setText(onlineApplyResponse.getAlgorithm());
//            extentionText.setText(onlineApplyResponse.getExtensions());
                String extension = onlineApplyResponse.getExtensions();
                String issueId = onlineApplyResponse.getApplyId();
                String subject = onlineApplyResponse.getSubject();
                String alAlgorithm = onlineApplyResponse.getAlgorithm();
                realName = realname;
                idNo = id;
                phone = tel;

                issueCertificate(userId, extension, issueId, subject, alAlgorithm);

            }

            @Override
            public void doCancel() {
                hideLoading();
                dimissProgress();
            }

            @Override
            public void doException(CmSdkException e) {
                hideLoading();
                Loger.e("--- registerCert--exception---" + e.getMessage());
                dimissProgress();
                Toast.makeText(RegisterCertActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        certificateRegisterService.register(param);
    }




    /**
     * 签发证书
     */
    private void issueCertificate(String userId, String extension, String issueId, String subject, String algotithm) {
        showLoading(getString(R.string.string_issuing));
        //   String userId = App.getUserId();
        cn.unitid.spark.cm.sdk.business.service.CertificateIssueService certificateIssueService = new cn.unitid.spark.cm.sdk.business.service.CertificateIssueService(RegisterCertActivity.this,
                userId, AppConstant.SPARK_RA_URL,  AppConstant.APP_KEY, AppConstant.APP_SECRET,
                new ProcessListener<OnlineIssueResponse>() {
                    @Override
                    public void doFinish(OnlineIssueResponse data, String cert) {
                        //  rxStyleDialogFragment.dismiss();
                        hideLoading();
                        String your_signature = data.getSignCert();
                        String your_encryption = data.getEncCert();

                        //证书签发成功，保存 真实name
                        if (!TextUtils.isEmpty(realName) && !TextUtils.isEmpty(idNo)) {
//                            MySpEdit.getInstance().setRealName(realName);
//                            MySpEdit.getInstance().setIDNo(idNo);
//                            MySpEdit.getInstance().setUser(phone);
                            prefs.setRealName(realName);
                            prefs.setIDNo(idNo);
                            prefs.setUser(phone);
                        }


                        if (!TextUtils.isEmpty(your_signature)) {
                            //  signatureCert.setText(your_signature);
                        }
                        if (!TextUtils.isEmpty(your_encryption)) {
                            //  encryptionCert.setText(your_encryption);
                        }
                        X509Certificate x509Certificate = null;
                        try {
                            x509Certificate = CertificateConverter.fromBase64(your_signature);
                            Loger.e("--cert");

                        } catch (CertificateException e) {
                            e.printStackTrace();
                        }
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

                        String validate = formatter.format(x509Certificate.getNotBefore()) + " - " + formatter.format(x509Certificate.getNotAfter());
                        // certValidate.setText(validate);
                        //注册成功，去加入公司 or注册公司
                        //  rxStyleDialogFragment.dismiss();


                        toActivity(LoginActivity.class);
                    }

                    @Override
                    public void doCancel() {
                        hideLoading();

                    }

                    @Override
                    public void doException(CmSdkException exception) {
                        hideLoading();

                        Loger.e("--- exceptionIssuse---" + exception.getMessage());
                        Toast.makeText(RegisterCertActivity.this, "" + exception.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
        //  String extension = extentionText.getText().toString();
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        Map<String, String> retMap = gson.fromJson(extension, new TypeToken<Map<String, String>>() {
        }.getType());
        // certificateIssueService.issue(issueId.getText().toString(), subject.getText().toString(),
        // retMap, algorithm.getText().toString(), true);
        certificateIssueService.issue(issueId, subject,
                retMap, algotithm.toString(), true);
    }

//    private void goRegisterCertify(String realname, String id, String tel, final String vcode) {
//        onlineClient = new OnlineClient(CertServiceUrl.baseUrl, CertServiceUrl.appKey, CertServiceUrl.appSecret);
//        CertificateRegisterService certificateRegisterService = new CertificateRegisterService(RegisterCertActivity.this,
//                onlineClient, new ProcessListener<OnlineApplyResponse>() {
//            @Override
//            public void doFinish(OnlineApplyResponse onlineApplyResponse, String cert) {
//
//                CertificateIssueService certificateIssueService = new CertificateIssueService(RegisterCertActivity.this, onlineClient, new ProcessListener<OnlineIssueResponse>() {
//                    @Override
//                    public void doFinish(OnlineIssueResponse data, String cert) {
////                        if (pdu.getMypDialog().isShowing()) {
////                            pdu.dismisspd();
////                        }
//                        MySpEdit.getInstance().setPinCode(vcode);
////                        private MySpEdit prefs;
////                        prefs = MySpEdit.getInstance();
//                        String spPinCode = MySpEdit.getInstance().getPinCode();
//
//                        Log.e("CertificateIssueService", "onFinish-- spPinCOde=" + spPinCode);
//
//                        String your_signature = data.getSignCert();
//                        String your_encryption = data.getEncCert();
//
//                        X509Certificate x509Certificate = null;
//                        try {
//                            x509Certificate = CertificateConverter.fromBase64(your_signature);
//
//                        } catch (CertificateException e) {
//                            e.printStackTrace();
//                        }
//
//                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//                        String validate = formatter.format(x509Certificate.getNotBefore()) + " - " +
//                                formatter.format(x509Certificate.getNotAfter());
//
////                        goToAddUser();
//                        //注册成功，去加入公司 or注册公司
//                        rxStyleDialogFragment.dismiss();
//                        toActivity(LoginActivity.class);
//
//                    }
//
//                    @Override
//                    public void doException(CmSdkException exception) {
////                        if (pdu.getMypDialog().isShowing()) {
////                            pdu.dismisspd();
////                        }
////                        dimissProgress();
//                        rxStyleDialogFragment.dismiss();
//                        Log.e("CertificateIssueService", "doException");
//                        SimpleToast.toastMessage(exception.getMessage(), Toast.LENGTH_SHORT);
//                        Toast.makeText(RegisterCertActivity.this, "" + exception.getMessage(), Toast.LENGTH_SHORT).show();
//                        Log.e("firstRegister", "showException" + exception.getMessage());
//                    }
//                });
//                String exts = onlineApplyResponse.getExtensions();
//                Gson gson = new GsonBuilder().disableHtmlEscaping().create();
//                Map<String, String> retMap = gson.fromJson(exts, new TypeToken<Map<String, String>>() {
//                }.getType());
//
//                certificateIssueService.issue(onlineApplyResponse.getApplyId(), onlineApplyResponse.getSubject(), retMap, onlineApplyResponse.getAlgorithm(), true);
//
//
//            }
//
//
//            @Override
//            public void doException(CmSdkException e) {
////
////                if (pdu.getMypDialog().isShowing()) {
////                    pdu.dismisspd();
////                }
////                dimissProgress();
//                rxStyleDialogFragment.dismiss();
//                Toast.makeText(RegisterCertActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT);
//                SimpleToast.toastMessage(e.getMessage(), Toast.LENGTH_SHORT);
//                Log.e("RegisterActivity", "CmSdkException" + e.getMessage());
//
//            }
//        });
//
//        try {
//
//            certificateRegisterService.register(realname, id, tel, vcode, null);
//        } catch (Exception e) {
//            Loger.e("==e--" + e);
//            // Toast.makeText(RegisterCertActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT);
//
////            dimissProgress();
//            Loger.e("=dissdialog--");
//            rxStyleDialogFragment.dismiss();
//            SimpleToast.toastMessage(e.getMessage(), Toast.LENGTH_SHORT);
//            e.printStackTrace();
//        }
//
//
//    }


    @Override
    protected void onDestroy() {
        hideLoading();
        super.onDestroy();
    }
}
